package home.study.xxy.bs.fifter;

import com.alibaba.fastjson.JSONObject;
import home.study.xxy.bs.entity.LoginUser;
import home.study.xxy.bs.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author xiaoxiangyu
 * @create 2022-05-26 19:32
 * @功能：
 */
@Component
@Slf4j
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {


        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            //不存在token
            filterChain.doFilter(request,response);
            return;
        }

        //解析token
        String id = JWTUtil.getUsername(token);
        
        //从redis获取user信息
        ;
//        System.out.println(o instanceof LoginUser);
        LoginUser loginUser = JSONObject.parseObject(String.valueOf(redisTemplate.opsForValue().get("login:" + token)), LoginUser.class);
//        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get("login:" + id);
        if (Objects.isNull(loginUser)){
            log.error("登录信息为空");
        }
        loginUser.setToken(token);


        //存在securityContextHolder  security其他的过滤器会从这个里面取出用户信息
        //最后个参数 权限信息
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);



        filterChain.doFilter(request,response);


    }
}
